<template>
  <n-grid :x-gap="12" :cols="12">
    <n-grid-item span="8" :offset="2">
      <div id="tradein-receipt">
        <div class="page-body">
          <div class="mb-4 font-bold text-2xl font-black">
            <span>回收订单回执</span>
          </div>
          <div class="flex justify-between items-center">
            <n-image
              width="80"
              src="https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg"
            />
            <div class="text-right">
              <div class="text-lg">
                <span>订单号: </span>
                <span class="font-bold">{{ purchaseInfo.num }}</span>
              </div>
              <div class="text-lg mt-1">
                <span>创建时间: </span>
                <span class="font-bold">{{ purchaseInfo.createTime }}</span>
              </div>
            </div>
          </div>
          <div class="mt-4">
            <span class="text-lg font-bold">订单交易项汇总</span>
          </div>
          <div class="mt-2">
            <div
              class="product-item"
              v-for="item in purchaseItems"
              :key="item.id"
            >
              <div class="product-info">
                <div>
                  <span>{{ item.variantName }}</span>
                </div>
                <div class="mt-1">
                  <span>序列号/IMEI: {{ item.snName[0] }}</span>
                </div>
              </div>
              <div class="product-amount">
                <span>X{{ item.quantity }}</span>
                <span>{{ currencyFormat(item.rowTotal) }}</span>
              </div>
            </div>
          </div>
          <div class="mt-2 price-info">
            <div class="price-money">
              <div class="price-item">
                <span class="price-item-label">应收总金额: </span>
                <span class="price-item-amount">
                  {{ currencyFormat(purchaseInfo.total) }}
                </span>
              </div>
              <div class="price-item border-b pb-2">
                <span class="price-item-label">实收总金额: </span>
                <span class="price-item-amount">
                  {{ currencyFormat(purchaseInfo.paidAmount) }}
                </span>
              </div>
              <div class="mt-2 mb-2">
                <span class="font-base font-black">商家付款明细</span>
              </div>
              <div v-for="item in paymentsList" :key="item.id" class="mb-2">
                <div class="price-item">
                  <span class="price-item-label"
                    >{{ getPaymentMethodName(item.method) }}:
                  </span>
                  <span class="price-item-amount">
                    {{ currencyFormat(item.amount) }}
                  </span>
                </div>
                <div class="text-right text-sm text-gray-500">
                  <span>{{ item.createTime }}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="mt-2 customer-store-info">
            <div>
              <div><span class="text-lg font-bold">客户信息</span></div>
              <div class="mt-1">
                <span class="text-base font-black">{{
                  customerInfo.name
                }}</span>
              </div>
              <div class="mt-1">
                <span class="text-gray-500">{{
                  customerInfo.phoneNumber
                }}</span>
              </div>
            </div>
          </div>
          <!-- <div class="mt-2">
            <div><span class="text-lg font-bold">商家信息</span></div>
            <div class="mt-1">
              <span class="text-base font-black">
                {{ companySettings.companyName || "/" }}
              </span>
            </div>
            <div class="mt-1">
              <span class="text-gray-500">
                {{ companySettings.address || "/" }}
              </span>
            </div>
          </div> -->
          <div class="mt-2 help-info">
            <div>
              <span class="text-gray-500">
                如遇到疑问，可以通过以下联系方式与我们取得联系：
              </span>
            </div>
            <div class="mt-2">
              <span class="text-gray-500">联系电话:</span>
              <span class="ml-2 font-black text-base font-bold">
                {{ companySettings.contactPhone || "/" }}</span
              >
            </div>
            <div class="mt-2" v-if="companySettings.contactEmail">
              <span class="text-gray-500">邮箱:</span>
              <span class="ml-2 font-black text-base font-bold">
                {{ companySettings.contactEmail || "/" }}
              </span>
            </div>
          </div>
          <div class="mt-2 help-info">
            <div v-html="tradeInTerm"></div>
          </div>
        </div>
      </div>
    </n-grid-item>
  </n-grid>

  <!-- 使用n-float-button替换原来的按钮 -->
  <n-float-button
    type="primary"
    @click="handlePrint"
    :right="30"
    :bottom="100"
    position="fixed"
  >
    <n-icon>
      <PrinterOutlined />
    </n-icon>
  </n-float-button>
</template>
<script setup lang="ts">
import { get } from "lodash-es";
import { ref, computed, onMounted } from "vue";
import { getTradeInReceiptData } from "@/api/tradein/tradein.api";
import {
  getCompanySetting,
  getTermsSettings,
} from "@/api/settings/settings.api";
import { getPaymentMethodName } from "@/common/utils/payment/index";
import { TradeInReceiptDataVO } from "@/types/model/tradein/vos/tradein.vo";
import { currencyFormat } from "@/common/utils/currencyFormatter/index.ts";
import { TERM_TYPE } from "@/constants/terms";
import printJS from "print-js";
import { PrinterOutlined } from "@vicons/antd"; // 导入打印图标

interface ITradeInReceiptProps {
  orderId: string;
}

const props = defineProps<ITradeInReceiptProps>();
const receiptData = ref<TradeInReceiptDataVO>({} as TradeInReceiptDataVO);
const companySettings = ref<any>({});
const tradeInTerm = ref<string>("");

const purchaseInfo = computed(() => {
  return get(receiptData.value, "posPurchase") || {};
});

const purchaseItems = computed(() => {
  return get(receiptData.value, "items") || [];
});

const customerInfo = computed(() => {
  return get(receiptData.value, "customer") || {};
});

const paymentsList = computed(() => {
  return get(receiptData.value, "payments") || [];
});

const init = async () => {
  const result = await getTradeInReceiptData(props.orderId);
  receiptData.value = get(result, "result") || {};

  const compSettingResult = await getCompanySetting();
  companySettings.value = get(compSettingResult, "result") || {};

  const termsResult = await getTermsSettings();
  const _termsSettings = get(termsResult, "result") || [];
  tradeInTerm.value = _termsSettings.find(
    (item: any) => item.type === TERM_TYPE.TRADE_IN
  )?.content;

  handlePrint();
};

onMounted(() => {
  init();
});

const handlePrint = () => {
  // 使用 print.js 打印指定 DOM 元素
  printJS({
    printable: "tradein-receipt",
    type: "html",
    css: "", // 可以添加额外的 CSS 文件路径
    scanStyles: true, // 自动扫描并应用元素上的样式
    targetStyles: ["*"], // 应用所有样式
    documentTitle: "回收订单回执", // 打印时的文档标题
    style: `
      @page {
        size: A4;
        margin: 0;
      }
      body {
        margin: 0;
        padding: 0;
      }
    `,
  });
};
</script>
<style lang="scss" scoped>
.page-body {
  background: #fff;
  padding: 20px;

  .product-item {
    @apply flex justify-between items-center border-b text-base pb-2;

    + .product-item {
      @apply mt-2;
    }

    .product-info {
      @apply flex-1;
    }

    .product-amount {
      @apply flex-1 flex flex-1 justify-between items-center font-bold text-slate-950;
    }
  }

  .price-info {
    @apply flex justify-end border-b;

    .price-money {
      @apply basis-1/2;

      .price-item {
        @apply flex justify-between items-center text-gray-500;
        line-height: 24px;

        .price-item-label {
          @apply basis-1/2 text-gray-500;
        }

        .price-item-amount {
          @apply text-black font-bold basis-1/2 text-right;
        }
      }
    }
  }

  .customer-store-info {
    @apply flex justify-between items-center border-b pb-2;

    > div {
      @apply flex-1;
    }
  }
}

#tradein-receipt {
  margin-top: 20px;
}

@media print {
  // 打印时隐藏浮动按钮
  .n-float-button {
    display: none !important;
  }

  /* 确保n-card及其所有父元素都可见 */
  .n-card,
  .n-card *,
  .page-body,
  .page-body * {
    color: #222;
    visibility: visible !important;
  }

  /* A4纸张设置 */
  @page {
    box-sizing: border-box;
    size: A4;
    margin: 10mm 15mm 10mm 15mm !important; /* 上 右 下 左 边距 */
  }

  body {
    margin: 0;
    padding: 0;
  }

  #tradein-receipt {
    width: 100% !important; /* 使用100%宽度，让@page的margin控制边距 */
    min-height: 297mm;
    padding: 0;
    margin: 0 auto;
    background: white;
  }

  .page-body {
    padding: 0 !important; /* 移除内部padding，使用@page的margin */
    margin: 0;
    width: 100%;
    box-sizing: border-box;
  }
}
</style>
